/*!
 * DOS WEB UI层处理定义文件
 *
 * 版权所有 2017 陈学芹 联系方式: 7219530@qq.com
 *
 * 本软件在GNU LGPL-V2.1协议下发布，欢迎使用.
 */
const express = require('express')
const router = express.Router()
require('./common')
const ddosOptions = {title: 'DDOS测试'}
const ConfigManager = require('../lib/config')
const _ = require('lodash')
const logger = require('../lib/logger')
const controller = require('../ddos/controller')
const FloodAgent = require('../ddos/agent')
const FloodListener = require('../ddos/listener')

controller.init()
let listener = new FloodListener(ConfigManager.getPort(), controller)
listener.start()

let agents = ConfigManager.getDdosAgents()
_.forEach(agents, function (agent) {
  controller.addAgent(new FloodAgent(agent))
})

router.get('/ui/ddos', function (req, res) {
  res.render('ddos', ddosOptions)
})

router.post('/api/ddos', function (req, res) {
  let hcode = 200
  logger.debug('ddos type %s target %s', req.body.type, req.body.target)
  let result
  try {
    controller.startFlood(req.body.target, {type: req.body.type, speed: req.body.speed})
    result = {}
  } catch (e) {
    result = e
    hcode = 500
  } finally {
    res.status(hcode).json(result)
  }
})

router.delete('/api/ddos', function (req, res) {
  let hcode = 200
  logger.debug('stop flood')
  let result
  try {
    controller.stopFlood()
    result = {}
  } catch (e) {
    result = e
    hcode = 500
  } finally {
    res.status(hcode).json(result)
  }
})

router.get('/api/ddos', function (req, res) {
  let result = controller.getState()
  res.status(200).json(result)
})

router.get('/api/ddos/traffic', function (req, res) {
  let result = controller.getTrafficStat()
  res.status(200).json(result)
})

module.exports = router
